<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8" />
		<meta name="viewport"
			content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<script src="./static/js/vue.min.js" charset="utf-8"></script>
		<script src="./static/js/jquery-3.5.1.min.js" charset="utf-8"></script>
		<script src="./static/js/axios.min.js" charset="utf-8"></script>
		<!-- uni 的 SDK -->
		<script type="text/javascript" src="./static/js/uni.webview.1.5.6.js"></script>
		<!-- <script src="https://cdn.bootcss.com/vConsole/3.3.4/vconsole.min.js"></script>
			<script>
				var vConsole = new VConsole();
			</script> -->
		<!-- 引入Cropper.js库 -->
		<link href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.css" rel="stylesheet">
		<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.js"></script>
		<link href="./static/css/index.css" rel='stylesheet' type='text/css'>
	</head>

	<body>
		<div id="app">
			<div class="camera-container">
				<template v-if="showCropper">
					<div class="crop-container">
						<img ref="cropImage" :src="photoDataUrl" alt="待裁剪的照片">
					</div>
					<div class="crop-controls">
						<button @click="cancelCrop" class="cancel">取消</button>
						<button @click="cropImage" class="confirm">确认裁剪</button>
					</div>
				</template>
				<template v-else-if="photoDataUrl">
					<div class="photo">
						<img :src="croppedDataUrl || photoDataUrl" alt="拍摄的照片">
					</div>
					<div class="controls">
						<button class="capture" @click="retakePhoto">重拍</button>
					</div>
				</template>
				<template v-else>
					<video ref="video" autoplay playsinline></video>
					<div class="overlay">
						<span>卡片放置区域不要有遮挡</span>
						<span>并且拍摄角度尽量垂直</span>
					</div>
					<div class="controls">
						<div class="capture-border">
							<button class="capture" @click="capturePhoto" :disabled="!isCameraActive">拍摄</button>
						</div>
					</div>
				</template>
				<canvas ref="canvas" style="display: none;"></canvas>
			</div>
		</div>
		<script>
			var App = new Vue({
				el: '#app',
				data() {
					return {
						stream: null,
						facingMode: 'environment', // 默认为后置摄像头
						isCameraActive: false,
						guideType: 'crosshair', // 默认显示十字线
						photoDataUrl: null,
						croppedDataUrl: null,
						showCropper: false,
						cropper: null
					}
				},
				methods: {
					async startCamera() {
						try {
							// 停止已有的流
							if (this.stream) {
								this.stream.getTracks().forEach(track => track.stop());
							}

							// 获取媒体设备
							this.stream = await navigator.mediaDevices.getUserMedia({
								video: {
									facingMode: this.facingMode,
									width: {
										ideal: 1280
									},
									height: {
										ideal: 720
									}
								},
								audio: false
							});

							this.$refs.video.srcObject = this.stream;
							this.isCameraActive = true;
						} catch (err) {
							console.error("摄像头访问错误:", err);
							alert("无法访问摄像头: " + err.message);
						}
					},
					capturePhoto() {
						if (!this.isCameraActive) return;
						const video = this.$refs.video;
						const canvas = this.$refs.canvas;
						// 设置canvas尺寸与视频相同
						canvas.width = video.videoWidth;
						canvas.height = video.videoHeight;
						// 在canvas上绘制视频帧
						const context = canvas.getContext('2d');
						context.drawImage(video, 0, 0, canvas.width, canvas.height);
						// 将canvas内容转换为图片并显示
						this.photoDataUrl = canvas.toDataURL('image/png');
						// 停止摄像头
						this.stream.getTracks().forEach(track => track.stop());
						this.isCameraActive = false;
						//开始裁剪
						this.startCrop()
					},
					retakePhoto() {
						this.photoDataUrl = null;
						this.croppedDataUrl = null;
						this.$nextTick(() => {
							this.startCamera();
						});
					},
					startCrop() {
						this.showCropper = true;
						this.$nextTick(() => {
							// 初始化Cropper
							const image = this.$refs.cropImage;
							this.cropper = new Cropper(image, {
								aspectRatio: 3 / 4,
								viewMode: 1,
								autoCropArea: 1,
								movable: false,
								zoomable: false,
								rotatable: false,
								scalable: false,
								guides: true,
								highlight: false,
								cropBoxMovable: true,
								cropBoxResizable: true,
								toggleDragModeOnDblclick: false,
							});
						});
					},
					cropImage() {
						if (this.cropper) {
							const canvas = this.cropper.getCroppedCanvas({
								width: 800,
								height: 600,
								minWidth: 400,
								minHeight: 300,
								maxWidth: 1200,
								maxHeight: 900,
								fillColor: '#fff',
								imageSmoothingEnabled: true,
								imageSmoothingQuality: 'high',
							});

							this.photoDataUrl = this.croppedDataUrl = canvas.toDataURL('image/png');
							this.showCropper = false;
							this.cropper.destroy();
							this.cropper = null;
						}
						//上传成功后返回
						uni.postMessage({
							data: {
								type: 'refreshData'
							}
						});
					},
					cancelCrop() {
						this.showCropper = false;
						if (this.cropper) {
							this.cropper.destroy();
							this.cropper = null;
						}
						this.retakePhoto()
					},
					confirmPhoto() {
						// 这里可以添加确认后的逻辑，比如上传图片等
						const finalImage = this.croppedDataUrl || this.photoDataUrl;
						alert('图片已确认，可以进行后续处理');
						console.log('确认的图片数据:', finalImage);
						// 示例：你可以在这里添加上传逻辑或触发父页面的事件
					},
					switchCamera() {
						if (!this.isCameraActive) return;
						// 切换摄像头模式
						this.facingMode = this.facingMode === 'user' ? 'environment' : 'user';
						// 重新启动相机
						this.startCamera();
					},
					getUrlParam(name) {
						var results = new RegExp("[?&]" + name + "=([^&#]*)").exec(
							window.location.href
						);
						if (results == null) {
							return null;
						}
						return decodeURIComponent(results[1]) || 0;
					}
				},
				mounted() {
					window.pageConfig = this.getUrlParam('pageConfig') ? JSON.parse(this.getUrlParam('pageConfig')) : {}
					document.title = window.pageConfig.name
					this.startCamera()
				},
				beforeDestroy() {
					// 组件销毁时停止摄像头
					if (this.stream) {
						this.stream.getTracks().forEach(track => track.stop());
					}
					// 销毁Cropper实例
					if (this.cropper) {
						this.cropper.destroy();
					}
				}
			});
		</script>
	</body>

</html>